<template>
  <div class="personal-container">
    <!-- 顶部背景 -->
    <div class="header-bg"></div>
    
    <!-- 用户信息卡片 -->
    <div class="user-card">
      <div class="user-avatar">
        {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
      </div>
      <div class="user-info">
        <h2 class="username">{{ userInfo.username || '加载中...' }}</h2>
        <p class="user-id">ID: {{ userInfo.id || '--' }}</p>
      </div>
    </div>

    <!-- 功能按钮区域 -->
    <div class="action-section">
      <div class="action-card">
        <button class="action-btn update-username-btn" @click="showUpdateUsername = true">
          <span class="btn-icon">👤</span>
          <span class="btn-text">修改用户名</span>
          <span class="btn-arrow">›</span>
        </button>
        
        <button class="action-btn update-password-btn" @click="showUpdatePassword = true">
          <span class="btn-icon">🔒</span>
          <span class="btn-text">修改密码</span>
          <span class="btn-arrow">›</span>
        </button>
        
        <button class="action-btn logout-btn" @click="showLogoutConfirm = true">
          <span class="btn-icon">🚪</span>
          <span class="btn-text">退出登录</span>
          <span class="btn-arrow">›</span>
        </button>
      </div>
    </div>

    <!-- 修改用户名弹窗 -->
    <div v-if="showUpdateUsername" class="modal-overlay" @click="showUpdateUsername = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">修改用户名</h3>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">用户名</label>
            <input 
              type="text" 
              class="form-input" 
              v-model="updateUsernameForm.username"
              placeholder="请输入用户名"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn cancel-btn" @click="showUpdateUsername = false">取消</button>
          <button class="btn confirm-btn" @click="handleUpdateUsername">确认</button>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div v-if="showUpdatePassword" class="modal-overlay" @click="showUpdatePassword = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">修改密码</h3>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">新密码</label>
            <input 
              type="password" 
              class="form-input" 
              v-model="updatePasswordForm.password"
              placeholder="请输入新密码"
            />
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn cancel-btn" @click="showUpdatePassword = false">取消</button>
          <button class="btn confirm-btn" @click="handleUpdatePassword">确认</button>
        </div>
      </div>
    </div>

    <!-- 退出登录确认弹窗 -->
    <div v-if="showLogoutConfirm" class="modal-overlay" @click="showLogoutConfirm = false">
      <div class="modal-content confirm-modal" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">退出登录</h3>
        </div>
        <div class="modal-body">
          <p class="confirm-text">确定要退出登录吗？</p>
        </div>
        <div class="modal-footer">
          <button class="btn cancel-btn" @click="showLogoutConfirm = false">取消</button>
          <button class="btn logout-confirm-btn" @click="handleLogout">确认退出</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiService } from '../utils/http'
import { tools } from '../utils/tools'

export default {
  name: 'Personal',
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    const userInfo = ref({})
    const showUpdateUsername = ref(false)
    const showUpdatePassword = ref(false)
    const showLogoutConfirm = ref(false)
    
    const updateUsernameForm = ref({
      username: ''
    })
    
    const updatePasswordForm = ref({
      password: ''
    })

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const headers = { token: `${tools.getTokenFromCookie()}` }
        const { res, isAuthenticated } = await tools.authApiCall(
          () => apiService.post('/PersonalQuery', { username: '' }, { headers }),
          router,
          route
        )
        
        if (res.data.data && res.data.data.length > 0) {
          userInfo.value = res.data.data[0]
          updateUsernameForm.value.username = userInfo.value.username
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }

    // 修改用户名
    const handleUpdateUsername = async () => {
      if (!updateUsernameForm.value.username.trim()) {
        alert('请输入用户名')
        return
      }

      try {
        const headers = { token: `${tools.getTokenFromCookie()}` }
        await tools.authApiCall(
          () => apiService.post('/UserRename', {
            username: updateUsernameForm.value.username
          }, { headers }),
          router,
          route
        )
        
        fetchUserInfo()
        showUpdateUsername.value = false
        alert('用户名修改成功')
      } catch (error) {
        console.error('修改用户名失败:', error)
        alert('修改用户名失败')
      }
    }

    // 修改密码
    const handleUpdatePassword = async () => {
      if (!updatePasswordForm.value.password.trim()) {
        alert('请输入新密码')
        return
      }

      try {
        const response = await apiService.getFresh('/PublicKeyQuery')
        if (response.data.key == "") {
          throw new Error('获取公钥失败')
        }
        // 加密密码
        const encryptedPassword = await tools.encryptPassword(response.data.key, updatePasswordForm.value.password)
        const headers = { token: `${tools.getTokenFromCookie()}` }
        await tools.authApiCall(
          () => apiService.post('/PasswordUpdate', {
            username: userInfo.value.username,
            password: encryptedPassword
          }, { headers }),
          router,
          route
        )
        
        showUpdatePassword.value = false
        updatePasswordForm.value.password = ''
        alert('密码修改成功')
      } catch (error) {
        console.error('修改密码失败:', error)
        alert('修改密码失败')
      }
    }

    // 退出登录
    const handleLogout = async () => {
      try {
        const headers = { token: `${tools.getTokenFromCookie()}` }
        await tools.authApiCall(
          () => apiService.post('/Logout', { username: userInfo.value.username }, { headers }),
          router,
          route
        )
        
        router.push('/login')
      } catch (error) {
        console.error('退出登录失败:', error)
        alert('退出登录失败')
      }
    }

    onMounted(() => {
      fetchUserInfo()
    })

    return {
      userInfo,
      showUpdateUsername,
      showUpdatePassword,
      showLogoutConfirm,
      updateUsernameForm,
      updatePasswordForm,
      handleUpdateUsername,
      handleUpdatePassword,
      handleLogout
    }
  }
}
</script>

<style scoped>
.personal-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  position: relative;
}

.header-bg {
  height: 200px;
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  border-radius: 0 0 30px 30px;
}

.user-card {
  background: white;
  margin: -80px 20px 20px 20px;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 10px 30px rgba(33, 150, 243, 0.2);
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: 600;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
}

.username {
  color: #1976d2;
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 4px 0;
}

.user-id {
  color: #757575;
  font-size: 14px;
  margin: 0;
}

.action-section {
  padding: 0 20px;
}

.action-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 20px rgba(33, 150, 243, 0.15);
}

.action-btn {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 20px 16px;
  border: none;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f5f5f5;
}

.action-btn:last-child {
  border-bottom: none;
}

.action-btn:hover {
  background: #f8fdff;
  transform: translateX(4px);
}

.btn-icon {
  font-size: 20px;
  margin-right: 12px;
  width: 24px;
  text-align: center;
}

.btn-text {
  flex: 1;
  text-align: left;
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.btn-arrow {
  color: #bdbdbd;
  font-size: 18px;
  font-weight: 600;
}

.update-username-btn:hover {
  border-left: 4px solid #4caf50;
}

.update-password-btn:hover {
  border-left: 4px solid #ff9800;
}

.logout-btn:hover {
  border-left: 4px solid #f44336;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 20px;
  width: 100%;
  max-width: 400px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}

.confirm-modal {
  max-width: 320px;
}

.modal-header {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  padding: 20px;
  text-align: center;
}

.modal-title {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.modal-body {
  padding: 24px;
}

.confirm-text {
  text-align: center;
  color: #666;
  font-size: 16px;
  margin: 0;
  line-height: 1.5;
}

.form-group {
  margin-bottom: 0;
}

.form-label {
  display: block;
  color: #333;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 16px;
  background: white;
  transition: all 0.3s ease;
  color: #333;
}

.form-input:focus {
  outline: none;
  border-color: #2196f3;
  box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
}

.form-input::placeholder {
  color: #bdbdbd;
}

.modal-footer {
  display: flex;
  gap: 12px;
  padding: 0 24px 24px 24px;
}

.btn {
  flex: 1;
  padding: 14px 20px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #eeeeee;
}

.confirm-btn {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
  color: white;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
}

.logout-confirm-btn {
  background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
  color: white;
}

.logout-confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(244, 67, 54, 0.3);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .header-bg {
    height: 180px;
    border-radius: 0 0 25px 25px;
  }
  
  .user-card {
    margin: -60px 16px 16px 16px;
    padding: 20px;
    border-radius: 16px;
  }
  
  .user-avatar {
    width: 60px;
    height: 60px;
    font-size: 20px;
  }
  
  .username {
    font-size: 20px;
  }
  
  .action-section {
    padding: 0 16px;
  }
  
  .action-btn {
    padding: 18px 14px;
  }
  
  .btn-text {
    font-size: 15px;
  }
  
  .modal-overlay {
    padding: 16px;
  }
  
  .modal-content {
    border-radius: 16px;
  }
  
  .modal-header {
    padding: 18px;
  }
  
  .modal-body {
    padding: 20px;
  }
  
  .modal-footer {
    padding: 0 20px 20px 20px;
  }
  
  .btn {
    padding: 12px 16px;
    font-size: 15px;
  }
}
</style>
